# _*_ coding:utf-8 _*_
# @Time  : 2023.10.09
# @Author: zizlee
import json
import datetime
import pathlib
import requests
from urllib3 import disable_warnings
disable_warnings()

HOST = 'https://210.13.218.130:9000/v1/'


class GFEX:
    delivery_address_url = 'http://www.gfex.com.cn/u/interfacesWebTcDeliveryQuotes/loadList'
    user_agent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/117.0.0.0 Safari/537.36 Edg/117.0.2045.60'

    def __init__(self, begin_month: str):
        self.begin_month = begin_month
        self.end_month = begin_month  # 只请求当月的

        save_folder = pathlib.Path(f'gfex/delivery')
        if not save_folder.exists():
            save_folder.mkdir(parents=True)

        resolve_folder = pathlib.Path(f'resolution/{self.month_last_date().strftime("%Y%m%d")}')
        if not resolve_folder.exists():
            resolve_folder.mkdir(parents=True)

        self.delivery_file_source = save_folder.joinpath(f'{self.month_last_date().strftime("%Y%m%d")}.json')
        self.delivery_file_resolution = resolve_folder.joinpath('GFE_Delivery.json')

    def month_last_date(self):
        m = int(self.begin_month[-2:])
        y = int(self.begin_month[:4])
        if m == 12:
            return datetime.date(y, m, 31)
        else:
            return datetime.date(y, m + 1, 1) + datetime.timedelta(days=-1)

    def get_delivery_file(self):
        r = requests.post(self.delivery_address_url, data={'begin_month': self.begin_month, 'end_month': self.end_month},
                          headers={'User-Agent': self.user_agent})
        res = r.json()

        with open(self.delivery_file_source, 'w', encoding='utf8') as f:
            json.dump(res, f, indent=2, ensure_ascii=False)
        print(f'获取{self.begin_month}的广期所交割数据成功!')

    def parse_delivery_file(self):
        if not self.delivery_file_source.exists():
            raise FileNotFoundError('还未获取交割原始数据文件!')
        with open(self.delivery_file_source, 'r', encoding='utf8') as f:
            d_data = json.load(f)
        month_last_date = self.month_last_date().strftime('%Y%m%d')
        res_data = []
        for row in d_data['data']:
            if row['variety'].find('小计') >= 0:
                v_en = row['varietyOrder'].upper().strip()
                if not v_en:
                    raise ValueError('解析品种代码出错!')
                res_data.append({
                    'variety_name': row['variety'].replace('小计', '').strip(),
                    'volume': float(row['deliveryQty']),
                    'amount': float(row['deliveryAmt']),
                    'variety_en': v_en,
                    'delivery_date': month_last_date,
                    'volume_unit': '手',
                    'amount_unit': '元'
                })

        with open(self.delivery_file_resolution, 'w', encoding='utf8') as f:
            json.dump(res_data, f, indent=2, ensure_ascii=False)

        print(f'解析{self.begin_month}的广期所交割数据成功,数量{len(res_data)}个!')

    def save_delivery(self):
        if not self.delivery_file_resolution.exists():
            raise FileNotFoundError('还未解析交割数据文件!')
        with open(self.delivery_file_resolution, 'r', encoding='utf8') as f:
            json_data = json.load(f)
        r = requests.post(url=HOST + 'exchange/delivery/', json=json_data, verify=False)
        print(r.json())


if __name__ == '__main__':
    handler = GFEX(begin_month='202311')
    handler.get_delivery_file()
    handler.parse_delivery_file()
    handler.save_delivery()
